<template>
  <div class="record-edit-container">
    <van-form @submit="onSubmit">
      <van-field
        v-model="formDisplay.account"
        label="账户"
        placeholder="请选择账户"
        readonly
        clickable
        @click="showAccountPicker = true"
        :error="!!accountError"
        :error-message="accountError"
      />
      <van-popup v-model:show="showAccountPicker" position="bottom" round>
        <van-picker
          title="选择账户"
          :model-value="pickerValue"
          :columns="accountColumns"
          @confirm="onAccountConfirm"
          @cancel="showAccountPicker = false"
          show-toolbar
        />
      </van-popup>
      
      <div class="form-field">
        <div class="field-row field-row-channel">
          <span class="field-label">渠道</span>
          <van-radio-group v-model="form.channel" direction="horizontal" class="radio-group channel-radio-group">
            <van-radio name="微信" icon-size="16px" class="channel-radio">微信</van-radio>
            <van-radio name="支付宝" icon-size="16px" class="channel-radio">支付宝</van-radio>
            <van-radio name="银行卡" icon-size="16px" class="channel-radio">银行卡</van-radio>
            <van-radio name="信用卡" icon-size="16px" class="channel-radio">信用卡</van-radio>
          </van-radio-group>
        </div>
      </div>
      
      <div class="form-field">
        <div class="field-row field-row-channel">
          <span class="field-label">类型</span>
          <van-radio-group v-model="form.type" direction="horizontal" class="radio-group channel-radio-group">
            <van-radio name="转入" icon-size="16px" class="channel-radio" checked-color="#27c19e">转入</van-radio>
            <van-radio name="转出" icon-size="16px" class="channel-radio" checked-color="#ff5b5b">转出</van-radio>
          </van-radio-group>
        </div>
      </div>
      
      <van-field
        v-model="form.amount"
        label="金额"
        type="number"
        placeholder="请输入金额"
        required
      />
      
      <van-field
        v-model="form.remark"
        label="备注"
        type="textarea"
        placeholder="请输入备注信息（选填）"
        rows="2"
        autosize
        maxlength="100"
        show-word-limit
      />
      
      <div style="margin: 24px 16px;">
        <van-button round block type="primary" native-type="submit">保存</van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Form, Field, Button, Popup, Picker, RadioGroup, Radio, showSuccessToast, showFailToast } from 'vant'
import { accountApi, recordApi } from '@/api'
import dateUtils from '@/utils/date'
import numberUtils from '@/utils/number'
import moneyUtils from '@/utils/money'

const route = useRoute()
const router = useRouter()
const accountError = ref('')
const pickerValue = ref([]);

// 表单数据
const form = reactive({
  account_id: null,
  channel: '微信',  // 默认值
  type: '转入',     // 默认值
  amount: null,
  remark: '',      // 备注字段
})

// 表单展示数据
const formDisplay = reactive({
  account: '',
})

// 原始账户数据
const accounts = ref([])

// 转换为 Picker 可用的格式
const accountColumns = computed(() => {
  return accounts.value.map(account => ({
    text: account.name,
    value: account.id
  }))
})

// 控制选择器显示
const showAccountPicker = ref(false)

// 获取账户列表
async function fetchAccounts() {
  try {
    const data = await accountApi.getAccounts()
    console.log('获取到的原始账户数据:', data)
    
    if (!data || data.length === 0) {
      accountError.value = '暂无可用账户，请先添加账户'
      showFailToast('暂无可用账户')
      return
    }
    
    accounts.value = data
  } catch (error) {
    console.error('获取账户失败:', error)
    showFailToast('获取账户列表失败')
  }
}

// 获取记录详情（编辑模式）
async function fetchRecord() {
  if (!route.params.id) return
  
  try {
    const data = await recordApi.getRecordDetail(route.params.id)
    console.log('获取记录:', data)
    
    // 设置提交数据
    form.account_id = data.account_id
    form.channel = data.channel
    form.type = data.type === 'in' ? '转入' : '转出'
    form.amount = data.amount
    form.remark = data.remark || ''
    
    // 设置展示数据
    const account = accounts.value.find(a => a.id === data.account_id)
    formDisplay.account = account ? account.name : ''
  } catch (error) {
    console.error('获取记录失败:', error)
    showFailToast('获取记录失败')
  }
}

// 初始化
onMounted(() => {
  fetchAccounts().then(() => {
    fetchRecord()
  })
})

// 账户选择回调
function onAccountConfirm({ selectedValues, selectedOptions }) {
  formDisplay.account = selectedOptions[0].text
  form.account_id = selectedOptions[0].value
  pickerValue.value = selectedValues
  showAccountPicker.value = false
}

// 提交表单
async function onSubmit() {
  if (!form.account_id) {
    showFailToast('请选择账户')
    return
  }
  
  try {
    const payload = {
      id: route.params.id || null,
      account_id: form.account_id,
      date: dateUtils.now(),
      amount: moneyUtils.formatMoney(form.amount),
      type: form.type === '转入' ? 'in' : 'out',
      channel: form.channel,
      remark: form.remark
    }
    
    await recordApi.createRecord(payload)
    showSuccessToast('保存成功')
    router.back()
  } catch (error) {
    console.error('保存失败:', error)
    showFailToast('保存失败')
  }
}
</script>

<style scoped>
.record-edit-container {
  min-height: 100vh;
  background: #f6f7fb;
  padding: 16px 0;
}

.form-field {
  padding: 10px 16px;
  background: #fff;
  position: relative;
}

.form-field:after {
  content: '';
  position: absolute;
  left: 16px;
  right: 16px;
  bottom: 0;
  height: 1px;
  background: #ebedf0;
  transform: scaleY(0.5);
}

.field-row {
  display: flex;
  align-items: center;
  min-height: 24px;
}

.field-label {
  width: 70px;
  font-size: 14px;
  color: #646566;
  flex-shrink: 0;
}

.radio-group {
  flex: 1;
  display: flex;
  justify-content: flex-start;
  gap: 16px;
  flex-wrap: nowrap;
}

.channel-radio-group {
  gap: 8px;
  min-width: 0;
}

.channel-radio {
  margin-right: 0;
  font-size: 13px;
  padding: 0;
}

/* Add field row class for channels specifically */
.field-row-channel {
  padding-right: 0;
}
</style> 